// pages/second/second.js
Page({


    /**
     * 页面的初始数据
     */
    data: {
        notifications: [{
                icon: "/image/消息页面-事件提醒.png",
                title: "事件提醒",
                url: "/pages/msg/SJTX/SJTX"
            },
            {
                icon: "/image/消息页面-紧急通知.png",
                title: "紧急通知",
                url: "/pages/msg/JJTZ/JJTZ"
            },
            {
                icon: "/image/消息页面-政策通知.png",
                title: "政策通知",
                url: "/pages/msg/ZCTZ/ZCTZ",
                policyList:[]
            },
            {
                icon: "/image/消息页面-事物通知.png",
                title: "事物通知",
                url: "/pages/msg/SWTZ/SWTZ",
                notice:[]
            }
        ], 
        eventReminders: [],
        urgentNotices: [],  
        others: [{
                url: "/pages/msg/PBTZ/PBTZ",
                icon: "/image/消息页面-排班通知.png",
                title: "排班通知"
            },
            {
                url: "/pages/msg/SBTZ/SBTZ",
                icon: "/image/消息页面-上班通知.png",
                title: "上班通知"
            },
            {
                url: "/pages/msg/GGTZ/GGTZ",
                icon: "/image/消息页面-公告通知.png",
                title: "公告通知"
            },
        ],
        tabs: [{
                id: 0,
                name: '事件提醒'
            },
            {
                id: 1,
                name: '紧急通知'
            },
            {
                id: 2,
                name: '政策通知'
            },
            {
                id: 3,
                name: '事物通知'
            }
        ],
        currentTab: 0,
  loading: {
      0: false,
      1: false,
      2: false,
      3: false
  },
  error: {
      0: false,
      1: false,
      2: false,
      3: false
  },
  errorMessage: ''
    },
    switchTab: function (e) {
      console.log(e.currentTarget.dataset.id);
        this.setData({
            currentTab: e.currentTarget.dataset.id
        });
    },

    others: [
      { url: "/pages/msg/PBTZ/PBTZ", icon: "/image/消息页面-排班通知.png", title: "排班通知" },
      { url: "/pages/msg/SBTZ/SBTZ", icon: "/image/消息页面-上班通知.png", title: "上班通知" },
      { url: "/pages/msg/GGTZ/GGTZ", icon: "/image/消息页面-公告通知.png", title: "公告通知" }
  ],
  tabs: [
      { id: 0, name: '事件提醒' },
      { id: 1, name: '紧急通知' },
      { id: 2, name: '政策通知' },
      { id: 3, name: '事物通知' }
  ],
  switchTab: function (e) {
    console.log('切换标签:', e.currentTarget.dataset.id);
    const tabId = e.currentTarget.dataset.id;
    this.setData({ currentTab: tabId });
    this.loadTabData(tabId);
},

loadTabData(tabId) {
    console.log(`加载标签 ${tabId} 数据`);
    const { loading, error } = this.data;
    if (loading[tabId] || error[tabId]) return;
    
    this.setData({ 
        loading: { ...loading, [tabId]: true },
        error: { ...error, [tabId]: false },
        errorMessage: ''
    });
    
    const loaders = {
        0: this.loadEventReminders,
        1: this.loadUrgentNotices
    };
    
    if (loaders[tabId]) {
        loaders[tabId]()
            .then(() => console.log(`标签 ${tabId} 数据加载成功`))
            .catch(err => {
                console.error(`标签 ${tabId} 数据加载失败:`, err);
                this.setData({
                    error: { ...error, [tabId]: true },
                    errorMessage: err.message || '加载失败，请重试'
                });
            })
            .finally(() => {
                this.setData({ loading: { ...loading, [tabId]: false } });
            });
    }
},

loadEventReminders() {
    return new Promise((resolve, reject) => {
        console.log('请求事件提醒数据...');
        wx.request({
            url: 'http://localhost:8080/eventReminders/selectAll',
            method: 'GET',
            success: (res) => {
                console.log('事件提醒响应:', res);
                if (res.statusCode === 200 && Array.isArray(res.data)) {
                    const reminders = res.data.map(item => ({
                        title: item.biaoti || '无标题',
                        date: item.createTime?.split(' ')[0] || '未知日期',
                        content: item.content || '无内容',
                        iconClass: 'icon-schedule'
                    }));
                    console.log('事件提醒数据处理完成:', reminders);
                    this.setData({ eventReminders: reminders });
                    resolve();
                } else {
                    reject(new Error(`加载失败，状态码: ${res.statusCode}`));
                }
            },
            fail: (err) => {
                console.error('事件提醒请求失败:', err);
                reject(err);
            },
            complete: () => {
                console.log('事件提醒请求完成');
            }
        });
    });
},

loadUrgentNotices() {
    return new Promise((resolve, reject) => {
        console.log('请求紧急通知数据...');
        wx.request({
            url: 'http://localhost:8080/urgentNotices/selectAll',
            method: 'GET',
            success: (res) => {
                console.log('紧急通知响应:', res);
                if (res.statusCode === 200 && Array.isArray(res.data)) {
                    const notices = res.data.map(item => ({
                        title: item.biaoti || '无标题',
                        date: item.createTime?.split(' ')[0] || '未知日期',
                        content: item.content || '无内容',
                        iconClass: 'icon-work'
                    }));
                    console.log('紧急通知数据处理完成:', notices);
                    this.setData({ urgentNotices: notices });
                    resolve();
                } else {
                    reject(new Error(`加载失败，状态码: ${res.statusCode}`));
                }
            },
            fail: (err) => {
                console.error('紧急通知请求失败:', err);
                reject(err);
            },
            complete: () => {
                console.log('紧急通知请求完成');
            }
        });
    });
},
retryLoad(e) {
  const tabId = e.currentTarget.dataset.id;
  this.setData({
      error: { ...this.data.error, [tabId]: false }
  });
  this.loadTabData(tabId);
},
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
      console.log('页面加载:', options);
      this.loadTabData(this.data.currentTab);
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
      const that = this
      wx.request({
        url: 'http://localhost:8080/policy/selectPolicy',
        success(res){
          console.log(res.data);
          that.setData({
            policyList:res.data
          })
        }
      });
      wx.request({
        url: 'http://localhost:8080/eventReminders/select',
        success(res){
          console.log(res.data);
          that.setData({
            notice:res.data
          })
        }
      })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

});